<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>fetch</title>
  </head>

  <body>
    <button class="btn1">发送GET请求</button>
    <button class="btn2">发送POST请求</button>
    <script>
      document.querySelector(".btn1").onclick = function () {
        fetch("http://localhost:3000/testFetch")
          .then((res) => {
            if (res.status >= 200 && res.status < 300) {
              // 请求成功
              return res.json();
            }
            // 请求失败
            return Promise.reject("请求失败了~");
          })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
      };

      document.querySelector(".btn2").onclick = function () {
        fetch("http://localhost:3000/testFetch", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ username: "admin" }),
        })
          .then((res) => {
            if (res.status >= 200 && res.status < 300) {
              // 请求成功
              return res.json();
            }
            // 请求失败
            return Promise.reject("请求失败了~");
          })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
      };
    </script>
  </body>
</html>
